//
//  DyJudgeIpAddressTool.m
//  OnlyRead
//
//  Created by Dyoung on 2017/8/13.
//  Copyright © 2017年 文得炙. All rights reserved.
//

#import "DyJudgeIpAddressTool.h"

@interface DyJudgeIpAddressTool ()


@end


@implementation DyJudgeIpAddressTool


+ (void)judgeIpAddressIsUSABlock:(returnBlock)block
{
    NSString * ipStr = [self getPublicIpStr];
    if ([ipStr hasPrefix:@"169.254"]) {//判断是否是私有iP地址。
        block(YES,ipStr);
        return;
    }
//    NSString * urlStr = [NSString stringWithFormat:@"http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=%@",@"17.199.223.172"];//美国地址测试;
     NSString * urlStr = [NSString stringWithFormat:@"http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=%@",ipStr];
    NSURL * URL = [NSURL URLWithString:urlStr];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:URL];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        NSString * dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"dataStr ====== %@",dataStr);
        
        if (connectionError) {
            block(YES,ipStr);
            return;
        }
        if ([self juedeIpIsBelongToUSAString:dataStr]) {
            block(YES,ipStr);
        }else{
            block(NO,ipStr);
        }
    }];
    
}


/**
 *  获取公网IP:
 *
 */
+ (NSString *)getPublicIpStr{
    NSURL *ipURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"]];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    NSString *ipStr = nil;
    if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功
        ipStr = ipDic[@"data"][@"ip"];
    }
    return (ipStr ? ipStr : @"");
}




+(BOOL)juedeIpIsBelongToUSAString:(NSString *)dataStr
{
    NSString * dicStr = [[dataStr componentsSeparatedByString:@"="] lastObject];
    dicStr = [dicStr substringToIndex:dicStr.length-1];

    NSError * err;
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:[dicStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
    if ([dic[@"country"] isEqualToString:@"美国"]) {
        return  YES;
    }
        return NO;
}



@end
